const ptRequest = require('pt-core-common').rpc.request;

const dispatcher = {};

const urlPrefix = "http://NLB-pt-core-feeds-16e79bf617c389c2.elb.us-east-2.amazonaws.com";
const portMapping = {
  "pt_core_feeds": 32780,
  "pt_core_market": 32782,
  "pt_core_operation": 32784,
  "pt_core_reports": 32786,
};

// const url_prefix_pt_core_feeds = "http://NLB-pt-core-feeds-16e79bf617c389c2.elb.us-east-2.amazonaws.com:32780";
// const url_prefix_pt_core_market = "http://NLB-pt-core-feeds-16e79bf617c389c2.elb.us-east-2.amazonaws.com:32782";
/* sample: feed completed notification from mws in sqs queue
<Notification>
    <NotificationMetaData>
        <NotificationType>FeedProcessingFinishedNotification</NotificationType>
        <PayloadVersion>1.0</PayloadVersion>
        <UniqueId>3dab6dbc-e451-43a2-8eb7-108fdcbb4f9d</UniqueId>
        <PublishTime>2020-12-06T07:02:33.793Z</PublishTime>
        <SellerId>A3C79HMK4O8JLQ</SellerId>
    </NotificationMetaData>
    <NotificationPayload>
        <FeedProcessingFinishedNotification>
            <SellerId>A3C79HMK4O8JLQ</SellerId>
            <FeedSubmissionId>50129018602</FeedSubmissionId>
            <FeedType>_POST_FLAT_FILE_INVLOADER_DATA_</FeedType>
            <FeedProcessingStatus>DONE</FeedProcessingStatus>
        </FeedProcessingFinishedNotification>
    </NotificationPayload>
</Notification>
*/
dispatcher.dispatch = async function(notification) {
  console.log(`received notification is: ${JSON.stringify(notification)}`);
  const notificationKey = Object.keys(notification.Notification.NotificationPayload)[0];
  if (notificationKey === "FeedProcessingFinishedNotification"){
    try {
      let json = {};
      if (notification.Notification.NotificationPayload.FeedProcessingFinishedNotification.FeedType === "_POST_FLAT_FILE_LISTINGS_DATA_") { // products feeds
        const sellerId = notification.Notification.NotificationPayload.FeedProcessingFinishedNotification.SellerId;
        const submissionId = notification.Notification.NotificationPayload.FeedProcessingFinishedNotification.FeedSubmissionId;
        json = await ptRequest("GET", `https://v68hs0jrzj.execute-api.us-east-2.amazonaws.com/prod/feeds/api/v1/feeds/submission/callback/${submissionId}`, {"sellerid": sellerId, "mwsauthtoken": "amzn.mws.c2b85f88-d34d-735b-6964-ac1d5f14086e"}, null);
      } else if (notification.Notification.NotificationPayload.FeedProcessingFinishedNotification.FeedType === "_POST_FLAT_FILE_INVLOADER_DATA_") { // inventory feeds
        console.log("feed type _POST_FLAT_FILE_INVLOADER_DATA_ has not implemented");
      }
      console.info(`rpc result is: ${JSON.stringify(json)}`);
    } catch (err) {
      console.error(err);
    }
  }
};

module.exports = dispatcher;